package servlet;

import domain.User;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取到用户输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //调用业务层
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.Login(username, password);
        //对user对象进行判断   要么是对象  要么是null
        if(user==null){
          //登录失败 用户名和密码错误了
            request.setAttribute("errorMsg","用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }else {
            //登录成功 把user存储到 HttpSession中
            request.getSession().setAttribute("user",user);
            //调转到系统首页
            request.getRequestDispatcher("/pages/home.jsp").forward(request,response);
            return;
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doPost(request,response);
    }
}
